package com.sh.粘包半粘包.two;

import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetServer;

/**
 * tcp服务端
 *
 * @author SH
 */
public class VertxTcpServer implements HttpServer {




    @Override
    public void doStart(int port) {
        // Vertx 实例
        Vertx vertx = Vertx.vertx();

        // tcp服务端
        NetServer server = vertx.createNetServer();

        // 处理请求
        server.connectHandler(socket -> {
            // 接收请求数据  处理连接  处理请求
            socket.handler(buffer -> {
                String message = "hello worldhello worldhello worldhello worldhello worldhello worldhello worldhello world";
                int length = message.getBytes().length;
                if (buffer.getBytes().length < length) {
                    System.out.println("半包， length" + buffer.getBytes().length);
                    return;
                }
                if (buffer.getBytes().length>length){
                    System.out.println("粘包， length" + buffer.getBytes().length);
                    return;
                }
                String str = new String(buffer.getBytes(0, length));
                System.out.println("收到正常请求数据===========" + str);

            });
        });


        // 启动服务器   监听端口
        server.listen(port, result -> {
            if (result.succeeded()) {
                System.out.println("tcp server is listening on port: " + port);
            } else {
                System.err.println("Failed to start the TCP server" + result.cause());
            }
        });
    }

    public static void main(String[] args) {
        new VertxTcpServer().doStart(8888);
    }


}
